<template>
  <div class="deposit-page">
    <div class="page-container">
      <div class="content-container">
        <div class="deposit-content">
          <!-- Deposit Card -->
          <div class="deposit-card">
            <!-- Title -->
            <h1 class="deposit-title">{{ $t('pages.deposit.title') }}</h1>

            <!-- Amount Display -->
            <div class="amount-display">
              <div class="amount-header">
                <div class="amount-label">{{ $t('pages.deposit.amountLabel') }}</div>
                <el-button
                  v-if="selectedAmount > 0"
                  text
                  type="danger"
                  size="small"
                  @click="resetAmount"
                  class="reset-btn"
                >
                  <Icon icon="mdi:refresh" width="14" height="14" />
                  {{ $t('pages.deposit.resetAmount') }}
                </el-button>
              </div>
              <div class="amount-value">{{ formatAmount(selectedAmount) }}</div>

              <div class="conversion-info">
                <div class="conversion-row">
                  <div class="row-label">{{ $t('pages.deposit.nearPriceLabel') }}</div>
                  <div class="row-value">
                    <template v-if="isPriceLoading">
                      <span class="state-text">{{ $t('pages.deposit.loadingPrice') }}</span>
                    </template>
                    <template v-else-if="priceLoadError">
                      <span class="state-text error">{{ $t('pages.deposit.priceLoadFailedShort') }}</span>
                    </template>
                    <template v-else>
                      <span class="price-text">₩{{ formatNearPrice(nearPrice) }}/NEAR</span>
                    </template>
                    <el-button
                      text
                      size="small"
                      class="refresh-price-btn"
                      :loading="isPriceLoading"
                      @click="loadNearPrice"
                    >
                      <Icon icon="mdi:refresh" width="14" height="14" />
                      {{ $t('pages.deposit.refreshPrice') }}
                    </el-button>
                  </div>
                </div>
                <div class="conversion-row">
                  <div class="row-label">{{ $t('pages.deposit.estimatedNearLabel') }}</div>
                  <div class="row-value">
                    <template v-if="estimatedNearAmount > 0">
                      ≈ {{ formatNearAmount(estimatedNearAmount) }}
                    </template>
                    <template v-else>
                      <span class="state-text">{{ $t('pages.deposit.selectAmountHint') }}</span>
                    </template>
                  </div>
                </div>
              </div>
            </div>

            <!-- Manual Input -->
            <div class="manual-input-section">
              <el-input
                v-model="manualAmount"
                :placeholder="$t('pages.deposit.manualInputPlaceholder')"
                size="large"
                class="manual-input"
                type="number"
                @keyup.enter="handleManualInput"
              >
                <template #append>
                  <el-button @click="handleManualInput" type="primary">
                    {{ $t('pages.deposit.confirmInput') }}
                  </el-button>
                </template>
              </el-input>
            </div>

            <!-- Amount Selection Grid -->
            <div class="amount-grid">
              <!-- 金额按钮 -->
              <button
                v-for="amount in amountOptions"
                :key="amount"
                :class="['amount-btn']"
                @click="selectAmount(amount)"
              >
                {{ formatAmount(amount) }}
              </button>

              <!-- 功能按钮：账户咨询 -->
              <button
                class="amount-btn function-btn inquiry-btn"
                @click="handleAccountInquiry"
              >
                <Icon icon="mdi:account-question" width="16" height="16" />
                {{ $t('pages.deposit.accountInquiry') }}
              </button>

              <!-- 功能按钮：修正（归零）-->
              <button
                class="amount-btn function-btn correction-btn"
                @click="handleCorrection"
              >
                <Icon icon="mdi:restart" width="16" height="16" />
                {{ $t('pages.deposit.correction') }}
              </button>
            </div>

            <!-- Action Buttons -->
            <div class="action-buttons">
              <el-button
                type="primary"
                size="large"
                class="deposit-btn"
                @click="handleDeposit"
                :disabled="!canSubmit"
                :loading="isSubmitting"
              >
                <Icon icon="mdi:plus" width="16" height="16" />
                {{ $t('pages.deposit.depositButton') }}
              </el-button>
              <el-button
                size="large"
                class="history-btn"
                @click="viewHistory"
              >
                <Icon icon="mdi:history" width="16" height="16" />
                {{ $t('pages.deposit.historyButton') }}
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { Icon } from '@iconify/vue'
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'
import { api } from '@/utils/request'
import { marketApiService } from '@/services/marketApi'
import { formatTokenAmount } from '@/utils/currency'

const { t } = useI18n()
const router = useRouter()

// 选中的金额
const selectedAmount = ref<number>(0)

// 预设金额选项（移除5亿和10亿）
const amountOptions = [
  10000,      // 10,000
  100000,     // 100,000
  1000000,    // 1,000,000
  10000000,   // 10,000,000
  50000000,   // 50,000,000
  100000000   // 100,000,000
]

// 格式化金额显示
const formatAmount = (amount: number): string => {
  if (amount === 0) return '0'
  return amount.toLocaleString('ko-KR')
}

const formatNearAmount = (amount: number): string => {
  return formatTokenAmount(amount, 'NEAR', 4)
}

const formatNearPrice = (price: number): string => {
  if (!price) return '0'
  return price.toLocaleString('ko-KR', {
    minimumFractionDigits: 0,
    maximumFractionDigits: 2
  })
}

// 选择金额（累加模式）
const selectAmount = (amount: number): void => {
  selectedAmount.value += amount
}

// 重置金额
const resetAmount = (): void => {
  selectedAmount.value = 0
}

// 账户咨询按钮
const handleAccountInquiry = (): void => {
  ElMessage.info(t('pages.deposit.accountInquiryMessage'))
}

// 修正按钮（归零）
const handleCorrection = (): void => {
  resetAmount()
  ElMessage.success(t('pages.deposit.correctionSuccess'))
}

// 手动输入金额
const manualAmount = ref<string>('')

// NEAR价格相关
const nearPrice = ref<number>(0)
const isPriceLoading = ref<boolean>(false)
const priceLoadError = ref(false)

const loadNearPrice = async (): Promise<void> => {
  try {
    isPriceLoading.value = true
    priceLoadError.value = false
    const priceData = await marketApiService.getNearPrice()
    nearPrice.value = priceData.price
  } catch (error) {
    console.error('NEAR 가격 조회 실패:', error)
    priceLoadError.value = true
    ElMessage.error(t('pages.deposit.priceLoadFailed'))
  } finally {
    isPriceLoading.value = false
  }
}

const estimatedNearAmount = computed(() => {
  if (!nearPrice.value || selectedAmount.value === 0) return 0
  return parseFloat((selectedAmount.value / nearPrice.value).toFixed(4))
})

const canSubmit = computed(() => {
  return selectedAmount.value > 0 && !!nearPrice.value
})

// 处理手动输入（累加模式）
const handleManualInput = (): void => {
  const amount = parseFloat(manualAmount.value)
  if (isNaN(amount) || amount <= 0) {
    ElMessage.warning(t('pages.deposit.invalidAmountWarning'))
    return
  }
  selectedAmount.value += amount
  manualAmount.value = ''
  ElMessage.success(t('pages.deposit.manualInputSuccess'))
}

// 处理充值申请
const isSubmitting = ref(false)

const handleDeposit = async (): Promise<void> => {
  if (!canSubmit.value) {
    ElMessage.warning(t('pages.deposit.selectAmountWarning'))
    return
  }

  try {
    isSubmitting.value = true
    const response = await api.post('/api/deposit/apply', {
      amount: selectedAmount.value,
      bankInfo: '은행 송금 충전'
    })

    if (response.success) {
      const lockedNear = response.data?.lockedNearAmount || 0
      const lockedPrice = response.data?.lockedNearPrice || nearPrice.value
      ElMessage.success(
        t('pages.deposit.depositSuccessNear', {
          amount: formatAmount(selectedAmount.value),
          near: formatNearAmount(lockedNear),
          price: formatAmount(Math.round(lockedPrice))
        })
      )
      selectedAmount.value = 0
      manualAmount.value = ''

      setTimeout(() => {
        viewHistory()
      }, 1500)
    }
  } catch (error) {
    console.error('충전 신청 실패:', error)
    ElMessage.error('충전 신청 제출에 실패했습니다. 잠시 후 다시 시도해 주세요.')
  } finally {
    isSubmitting.value = false
  }
}

// 查看充值历史
const viewHistory = (): void => {
  router.push('/app/deposit/history')
}

// 页面初始化
onMounted(async () => {
  document.title = '충전 - MyNearWallet'
  await loadNearPrice()
})
</script>

<style scoped lang="scss">
.deposit-page {
  background: #f8fafc;
  min-height: 100vh;
  padding: 40px 0;
}

.page-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 24px;
}

.content-container {
  max-width: 800px;
  margin: 0 auto;
}

.deposit-content {
  .deposit-card {
    background: white;
    border-radius: 16px;
    padding: 48px 32px;
    text-align: center;
    box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
    border: 1px solid #e2e8f0;

    .deposit-title {
      font-size: 28px;
      font-weight: 600;
      color: #1a202c;
      margin: 0 0 32px 0;
    }

    .amount-display {
      margin-bottom: 20px;
      padding: 24px;
      background: #f8fafc;
      border-radius: 12px;
      border: 1px solid #e2e8f0;

      .amount-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 8px;
      }

      .amount-label {
        font-size: 14px;
        color: #64748b;
      }

      .reset-btn {
        font-size: 12px;
        padding: 4px 8px;
        display: flex;
        align-items: center;
        gap: 4px;
      }

      .amount-value {
        font-size: 32px;
        font-weight: 600;
        color: #1a202c;
        font-family: 'Courier New', monospace;
      }

      .conversion-info {
        margin-top: 16px;
        padding: 12px 16px;
        border: 1px dashed #dbeafe;
        border-radius: 10px;
        background: #fff;
        display: flex;
        flex-direction: column;
        gap: 8px;

        .conversion-row {
          display: flex;
          justify-content: space-between;
          align-items: center;
          gap: 16px;

          .row-label {
            font-size: 13px;
            color: #64748b;
            font-weight: 500;
          }

          .row-value {
            font-size: 14px;
            color: #1f2937;
            display: flex;
            align-items: center;
            gap: 12px;

            .state-text {
              color: #94a3b8;

              &.error {
                color: #ef4444;
              }
            }

            .price-text {
              font-weight: 600;
              color: #0f172a;
            }

            .refresh-price-btn {
              padding: 0;
              color: #2563eb;

              &:hover {
                color: #1d4ed8;
              }
            }
          }
        }
      }
    }

    .manual-input-section {
      margin-bottom: 24px;

      .manual-input {
        :deep(.el-input-group__append) {
          background: #7c3aed;
          border-color: #7c3aed;

          .el-button {
            background: transparent;
            border: none;
            color: white;
            font-weight: 600;

            &:hover {
              background: rgba(255, 255, 255, 0.1);
            }
          }
        }

        :deep(.el-input__inner) {
          text-align: center;
          font-size: 16px;
          font-weight: 600;
        }
      }
    }

    .amount-grid {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      gap: 12px;
      margin-bottom: 32px;

      .amount-btn {
        background: #fbbf24;
        border: none;
        border-radius: 8px;
        padding: 16px 12px;
        font-weight: 600;
        color: #1a202c;
        cursor: pointer;
        transition: all 0.2s ease;
        font-size: 14px;
        min-height: 56px;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 6px;

        &:hover {
          background: #f59e0b;
          transform: translateY(-2px);
          box-shadow: 0 4px 8px rgba(251, 191, 36, 0.3);
        }

        &:active {
          transform: translateY(0);
        }

        // 功能按钮样式
        &.function-btn {
          font-weight: 500;
          font-size: 13px;
        }

        // 账户咨询按钮（蓝色）
        &.inquiry-btn {
          background: #3b82f6;
          color: white;

          &:hover {
            background: #2563eb;
            box-shadow: 0 4px 8px rgba(59, 130, 246, 0.3);
          }
        }

        // 修正按钮（灰色）
        &.correction-btn {
          background: #6b7280;
          color: white;

          &:hover {
            background: #4b5563;
            box-shadow: 0 4px 8px rgba(107, 114, 128, 0.3);
          }
        }
      }
    }

    .action-buttons {
      display: flex;
      gap: 16px;
      justify-content: center;
      flex-wrap: wrap;

      .deposit-btn {
        background: #7c3aed;
        border: none;
        padding: 16px 32px;
        font-weight: 600;
        font-size: 16px;
        border-radius: 8px;
        color: white;
        min-width: 140px;

        &:hover:not(:disabled) {
          background: #6d28d9;
        }

        &:disabled {
          background: #cbd5e1;
          color: #9ca3af;
          cursor: not-allowed;
        }
      }

      .history-btn {
        border: 1px solid #d1d5db;
        color: #374151;
        padding: 16px 32px;
        font-weight: 600;
        font-size: 16px;
        border-radius: 8px;
        background: white;
        min-width: 140px;

        &:hover {
          border-color: #7c3aed;
          color: #7c3aed;
          background: rgba(124, 58, 237, 0.05);
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .page-container {
    padding: 16px;
  }

  .deposit-card {
    padding: 32px 20px !important;

    .deposit-title {
      font-size: 24px !important;
    }

    .amount-display {
      padding: 20px !important;

      .amount-value {
        font-size: 28px !important;
      }
    }

    .amount-grid {
      grid-template-columns: repeat(2, 1fr) !important;
      gap: 8px !important;

      .amount-btn {
        padding: 12px 8px !important;
        font-size: 12px !important;
        min-height: 48px !important;
      }
    }

    .action-buttons {
      flex-direction: column;

      .el-button {
        width: 100%;
        min-width: unset !important;
      }
    }
  }
}

@media (max-width: 480px) {
  .deposit-page {
    padding: 20px 0;
  }

  .page-container {
    padding: 12px;
  }

  .deposit-card {
    padding: 24px 16px !important;

    .amount-grid {
      .amount-btn {
        font-size: 11px !important;
        padding: 10px 6px !important;
        min-height: 44px !important;
      }
    }
  }
}
</style>
